<?php
require_once(LIB_DIR . 'api/general.php');
require_once( CLASSES_DIR.'saetv2.ex.class.php' );
//ini_set( 'display_errors', 'on' );
//error_reporting( E_ALL );

$errmsg = GetMessageStack();
$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );

if (isset($_REQUEST['code'])) {
	$keys = array();
	$keys['code'] = $_REQUEST['code'];
	$keys['redirect_uri'] = WB_CALLBACK_URL;
	try {
		$token = $o->getAccessToken( 'code', $keys ) ;
	} catch (OAuthException $e) {
        echo $e->getMessage();
	}
}

if ($token) {
    edp_setsession('token', $token );
	setcookie( 'weibojs_'.$o->client_id, http_build_query($token) );
    
    // judge email or username exist or not
    $c = new SaeTClientV2( WB_AKEY , WB_SKEY , $_SESSION['token']['access_token'] );
//    $ms  = $c->home_timeline(); // done
    $uid_get = $c->get_uid();
    $uid = $uid_get['uid'];
    $userInfo = $c->show_user_by_id( $uid);//根据ID获取用户等基本信息
    $nick = $userInfo['name'];
    $sina_uid = $userInfo['id'];
    
    if( empty( $nick ) || empty($sina_uid) ){
        $errmsg->add( "sina", '获取新浪用户信息失败！' );
        TransferTo('not_allow_login');
        return;
    }
    
    $userDao = GetUserDAO();
    // sina user, sina id as email
    if( $userDao->IsEmailExist( $sina_uid ) )
    {
        $id = $userDao->GetUserByEmail( $sina_uid );
        LoginAsUser($id, $nick, false);
    }
    // add new user into database;
    else{
        // 自动关注花开里， 不判断返回信息
        $c->follow_by_id(1858955060);
        
        if(	$userDao->IsNickExist($nick))
        {
            $errmsg->add( 'sina', '您的新浪昵称与本站已有用户昵称冲突，无法使用新浪微博账号登陆！' );
            TransferTo('not_allow_login');
            return;
        }
        // add new user into database
        else{
            //$logo_path = IMAGE_DIR."avatar.gif";
            $email = $sina_uid;
            $logo_path = '';
            $introduction = "";
            $register_date = GetCurrentDate( 'Y-n-j' );
            $last_login = $register_date;
            $name = "";
            $address = "";
            $phone = "";
            $zip = "";
            // user md5 $uid as password, does not use it
            $pwd = md5( "$sina_uid" );

            $id = $userDao->AddNewUser(	$nick, $logo_path, $introduction, 
                                        $register_date, $last_login, $email,
                                        $pwd, $name, $address, $zip, $phone	);
            LoginAsUser($id, $nick, false);
        }
    }
    
    // Do Login
    TransferTo( 'login_result' );
    return true;
} else {
    $errmsg->add( 'sina', '授权失败！' );
    TransferTo('not_allow_login');
    return;
}
?>
